﻿using System.Collections.ObjectModel;
using Microsoft.VisualBasic.ApplicationServices;
using MouseExtender.Logic.Managers;

namespace MouseExtender.Logic
{
    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        private App _application = null;
        private static bool _isAutoStarted = false;

        public static bool IsAutoStarted
        {
            get { return _isAutoStarted; }
            set { _isAutoStarted = value; }
        }

        public static bool IsUpdated
        {
            get;
            set;
        }

        internal SingleInstanceManager()
        {
            IsSingleInstance = true;
        }

        private bool HasAutostartCommand(ReadOnlyCollection<string> commandArgs)
        {
            return commandArgs.Contains(Constants.AutoStartCommandArg);
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            // First time app is launched
            IsAutoStarted = HasAutostartCommand(e.CommandLine);
            IsUpdated = e.CommandLine.Contains(Constants.UpdatedCommandArg);
            ResourceManager.SetCulture();
            _application = new App();
            _application.InitializeComponent();
            _application.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);

            if (!HasAutostartCommand(eventArgs.CommandLine))
                _application.Activate();
        }

        internal static void RestartApplication()
        {
            System.Windows.Application.Current.Shutdown();
            System.Windows.Forms.Application.Restart();
        }
    }
}